package com.fqdf.framework.android.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

public class CountDownTextView extends AppCompatTextView {

    private String originText;

    public CountDownTextView(Context context) {
        super(context);
    }

    public CountDownTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CountDownTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
    }

    public void startCountDown(final int countDown) {
        if (countDown <= 0) {
            return;
        }

        if (originText == null) {
            originText = getText().toString();
        }

        setText(originText + "" + countDown);
        final long startTime = System.currentTimeMillis();
        postDelayed(new Runnable() {
            @Override
            public void run() {
                long curTime = System.currentTimeMillis();
                long timeSpace = (curTime - startTime) / 1000;

                int showTime = countDown - (int) timeSpace;
                if (showTime > 0) {
                    setText(originText + "" + countDown);
                    postDelayed(this, 100);
                }

            }
        }, 100);
    }
}
